package com.jquerymobile.demo.contact;

import org.codehaus.jackson.map.ObjectMapper;

import android.accounts.Account;
import android.accounts.AccountManager;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.webkit.WebView;

public class ContactsActivity extends Activity {
	WebView webView;
	private String accountType = null;
	private String accountName = null;
	private static final String JAVASCRIPT = "javascript:";
	private static final String BRC = "()";
	private static final String BRC_OPEN = "('";
	private static final String BRC_CLOSE = "')";
	private static final String Q = "?";
	private static final String HTML_ROOT = "file:///android_asset/www/";		

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        accountType = "com.jquerymobile.demo.contact";
        Account[] accounts = AccountManager.get(this).getAccountsByType (accountType);
        if(accounts.length != 0){
        	accountName = accounts[0].name;
        }        
        
        setContentView(R.layout.my);
        webView = (WebView) findViewById(R.id.webview);
        webView.getSettings().setJavaScriptEnabled(true);
        webView.addJavascriptInterface(new JavaScriptInterface(this), "contactSupport"); 
        webView.loadUrl(HTML_ROOT + "index.html");
    }
    
    public boolean onCreateOptionsMenu(Menu menu){

    	MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu, menu);

    	return true;
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle item selection
        switch (item.getItemId()) {
            case R.id.exit:
            	System.exit(0);
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }    
    
    public class JavaScriptInterface {
        Context mContext;
 
        /** Instantiate the interface and set the context */
        JavaScriptInterface(Context c) {
            mContext = c;
        }
        
        public void loadPage(String in){    	
        	webView.loadUrl(HTML_ROOT + in);
        }
        
        private void loadURL(String in){    	
        	webView.loadUrl(in);
        }
        
        public void createAccount(String accountN, String displayPage){
        	if(accountN != null && !ContactUtility.EMPTY.equals(accountN)){
        		accountName = accountN;
        		AccountManager.get(mContext).addAccountExplicitly(new Account(accountName,accountType), "dummyPassword", null);   
        	}
        	loadPage(displayPage);
        }
        
        public void deleteAccount(String displayPage){
        	if(accountName != null){
        		Account[] accounts = AccountManager.get(mContext).getAccounts();
        		for (android.accounts.Account account: accounts) { 
        			if(account.name.equals(accountName))
        				AccountManager.get(mContext).removeAccount(account, null, null); 
        	    }
        	}
        	loadPage(displayPage);
        }        

        public void deleteContact(String contactId, String displayPage){   
        	ContactUtility.deleteContact(contactId,getContentResolver(),accountType);    	
        	loadPage(displayPage);
        }
        
        public void showAllContacts(String displayPage){    	
        	loadPage(displayPage);   	
        }
        
        public void showContact(String contactId, String displayPage){    	
        	loadPage(displayPage + Q + contactId);	
        }
        
        public void getContact(String contactId,String contactCallback){
        	String json = ContactUtility.getContactJSON(contactId, getContentResolver()); 
        	final String callbackFunction = JAVASCRIPT + contactCallback + BRC_OPEN + json 
        		+ BRC_CLOSE;
        	loadURL(callbackFunction); 	  	
        }

        public void addContact(String displayPage){    	
        	showContact(ContactUtility.EMPTY, displayPage);
        }
        
        public void getAllContacts(String callback, String accountCallback){    	
        	final String accountCallbackFunction = JAVASCRIPT + accountCallback + BRC;
        	
        	if(accountName == null){
        		loadURL(accountCallbackFunction);
        		return;
        	}
        	final String json = ContactUtility.getAllContactDisplaysJSON(getContentResolver());
        	final String callbackFunction = JAVASCRIPT + callback + BRC_OPEN + json + BRC_CLOSE;
        	loadURL(callbackFunction); 	
        }

        public void saveContact(String json, String displayPage){
        	ObjectMapper mapper = new ObjectMapper();
        	try{
        		Contact c = mapper.readValue(json,Contact.class);
        		ContactUtility.saveOrUpdateContact(c, getContentResolver(), accountName, accountType);
        	}catch(Exception e){
        		e.printStackTrace();
        	}
        	loadPage(displayPage);
        }        
    }
 
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // Check if the key event was the BACK key and if there's history
        if ((keyCode == KeyEvent.KEYCODE_BACK) && webView.canGoBack()) {
        	webView.goBack();
            return true;
        }
        // If it wasn't the BACK key or there's no web page history, bubble up to the default
        // system behavior (probably exit the activity)
        return super.onKeyDown(keyCode, event);
    }
}